package com.example.facecompare.common.tool.file;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.facecompare.common.tool.result.Result;
import com.example.facecompare.user.img.entity.UserCompareInfo;
import com.example.facecompare.user.img.entity.UserImg;
import com.example.facecompare.user.img.service.IUserImgService;
import com.example.facecompare.user.userinfo.entity.User;
import com.example.facecompare.user.userinfo.mapper.UserMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class FileScanner {
    @Value("${url.sjht}")
    private String sjhtUrl;

    @Autowired
    private IUserImgService iUserImgService;

    @Autowired
    private UserMapper userMapper;

    @SneakyThrows
    public static List<String> getAllImageFilePaths(String directoryPath) {
        List<String> filePaths = new ArrayList<>();

        // 获取目录路径
        Path directory = Paths.get(directoryPath);

        // 递归遍历目录下的所有文件和子目录
        Files.walk(directory)
                .filter(Files::isRegularFile) // 过滤出普通文件
                .filter(file -> file.toString().toLowerCase().endsWith(".jpg") || file.toString().toLowerCase().endsWith(".png") ||
                        file.toString().toLowerCase().endsWith(".jpeg")) // 过滤出图片文件
                .forEach(file -> filePaths.add(file.toString())); // 添加文件路径到列表

        return filePaths;
    }

    /**
     * 条件获取要对比的图片
     * @param directoryPath 基本库路径
     * @param passOpenid 选择审核通过或为null的时候无论审核是否通过都进行对比，默认选择审核通过的
     * @return
     */
    @SneakyThrows
    public List<String> getPassImageFilePaths(String directoryPath, List<String> passOpenid) {
        List<String> filePaths = new ArrayList<>();
        if (passOpenid==null){
            passOpenid = new ArrayList<>();
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("info_check",1);
//            userMapper.selectList(queryWrapper);
            for (User u:userMapper.selectList(queryWrapper)) {
                passOpenid.add(u.getOpenid());
            }
        }

        Path directory = Paths.get(directoryPath);
        List<String> finalPassOpenid = passOpenid;
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                // 过滤掉不是 "tbb" 和 "tsl" 目录
                    if (finalPassOpenid.contains(dir.getFileName().toString())||dir.getFileName().toString().equals("face")) {
//                        log.info(dir.getFileName().toString());
                        return FileVisitResult.CONTINUE; // 进入目录继续遍历
                    } else {
//                        log.info(dir.getFileName().toString());
//                        log.info(finalPassOpenid+"");
                        return FileVisitResult.SKIP_SUBTREE; // 跳过子目录
                    }

            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
                // 过滤出图片文件
                if (file.toString().toLowerCase().endsWith(".jpg")
                        || file.toString().toLowerCase().endsWith(".png")
                        || file.toString().toLowerCase().endsWith(".jpeg")) {
                    filePaths.add(file.toString()); // 添加文件路径到列表
                }
                return FileVisitResult.CONTINUE;
            }
        });

        // 打印找到的图片文件路径
//        for (String filePath : filePaths) {
//            System.out.println(filePath);
//        }
        return filePaths;
    }

    @SneakyThrows
    public Object getCompareResult(File filePath,String bashPath,List<String> allImageFilePaths,Float revalue){


        String inputPath = filePath.getPath();

        String input;
        String key = "";
        float value;
        float max = 0.0f;
        File comparePath = null;
        User user = null;
        log.info(allImageFilePaths.size()+"");
        for (String path : allImageFilePaths) {
            StringBuffer compareResult;

            compareResult = iUserImgService.getCompareResult(bashPath, inputPath, path);

            input = String.valueOf(compareResult);
            Pattern pattern = Pattern.compile("'(.*?)': ([\\d.]+)");
            Matcher matcher = pattern.matcher(input);
            if (matcher.find()) {
                key = matcher.group(1);
                value = Float.parseFloat(matcher.group(2));
                if (max < value && value > revalue) {
                    max = value;
                    File file2 = new File(path);
                    comparePath = new File(sjhtUrl, key + "/" + file2.getName());
                    user = userMapper.selectById(key);
                }
                log.info("Key: " + key);
                log.info("Value: " + value);
            }
        }
        if (user == null) {
            return "无该用户信息";
        }
        UserCompareInfo userCompareInfo = new UserCompareInfo();
        userCompareInfo.setUname(user.getUname());
        userCompareInfo.setEmail(user.getEmail());
        userCompareInfo.setInGroup(user.getInGroup());
        userCompareInfo.setPhone(user.getPhone());
        userCompareInfo.setJoinTime(user.getJoinTime());
        userCompareInfo.setPosition(user.getPosition());
        userCompareInfo.setSection(user.getSection());
        userCompareInfo.setSex(user.getSex());
        userCompareInfo.setCompareImg(comparePath.getPath());
        userCompareInfo.setCompareValue(max);

        return userCompareInfo;
    }

    @SneakyThrows
    public Object getCompareResult(String base64,String bashPath,String outPath){

        StringBuffer compareResult = iUserImgService.getCompareResult(bashPath, base64, outPath);

        String openid = String.valueOf(compareResult);
        log.info(openid);
        if (openid.equals("")||openid.equals("unknown")){
            return null;
        }
        User user = userMapper.selectById(openid);
        UserCompareInfo userCompareInfo = new UserCompareInfo();
        userCompareInfo.setOpenid(openid);
        userCompareInfo.setUname(user.getUname());
        userCompareInfo.setEmail(user.getEmail());
        userCompareInfo.setInGroup(user.getInGroup());
        userCompareInfo.setPhone(user.getPhone());
        userCompareInfo.setJoinTime(user.getJoinTime());
        userCompareInfo.setPosition(user.getPosition());
        userCompareInfo.setSection(user.getSection());
        userCompareInfo.setSex(user.getSex());
//        userCompareInfo.setCompareImg(comparePath.getPath());
//        userCompareInfo.setCompareValue(max);

        return userCompareInfo;
    }
}